<?php
/**
 * Created by PhpStorm.
 * User: xloong
 * Date: 2017/7/26
 * Time: 15:46
 */

namespace App\Http\Controllers\Api\V1;


use App\Models\Article;
use App\Models\Category;
use App\Models\UserFavorite;
use Illuminate\Http\Request;

class ArticleController extends BaseController
{
    //分页条数
    const PAGE_SIZE=10;
    //默认第一条分类名称
    const INDEX_CATEGORY="推荐";
    private $result = array('code' => '10000', 'message' => '系统服务异常', 'data' => array());

    /**
     * @api {post} /article 1. 获取推荐内容(article)
     * @apiDescription
     * 获取推荐内容。
     * @apiGroup user
     * @apiPermission none
     * @apiVersion 0.1.0
     * @apiParam {Number{..11}} category_id  文章分类id
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *      {
     *          "code": 200,
     *          "message": "获取分类内容成功",
     *          "data": []
     *      }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code": 21101,
     *          "message": "参数错误",
     *          "data": []
     *     }
     */
    public function getArticle(Request $request){
        // 自定义验证规则
        $rules = [
            'category_id' => 'integer',
        ];
        // 自定义提示
        $messages = [
            'category_id.integer' => ['code' => 21101,  'message' => ':attribute 格式错误.', 'data' => []],
        ];
        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }

        $categoryId   = $request->get('category_id');
        $searchTitle  = $request->get('search_title');
        $category = Category::orderBy('sort')->get()->toArray();
        //下面这个代码不删除是怕客户反悔
        //array_unshift($category,['id'=>'','name'=>self::INDEX_CATEGORY,'sort'=>'','slug'=>'']);
        //判断用户是否输入了搜索关键字
        if(!empty($searchTitle)){
            $indexArticles = Article::where('title','like','%'.e($searchTitle).'%')->orderBy('created_at','desc')
                             ->paginate(self::PAGE_SIZE);
        }else{
            //判断是否传入分类id，然后以此做为查询条件
            if(empty($categoryId)){
                $indexArticles = Article::where('cid',current($category)['id'])->orderBy('is_top','desc')
                    ->orderBy('created_at','desc')
                    ->paginate(self::PAGE_SIZE);
            }else{
                $indexArticles = Article::where('cid',$categoryId)->orderBy('is_top','desc')
                    ->orderBy('created_at','desc')
                    ->paginate(self::PAGE_SIZE);
            }
        }
        //查找文章对应缩略图信息
        if(!empty($indexArticles)){
            foreach ($indexArticles as $key=>$indexArticle){
                if(!$indexArticle->image->isEmpty()){
                    $indexArticles[$key]['thumb']  = array_column($indexArticle->image->toArray(),'url');
                }else{
                    $indexArticles[$key]['thumb']  = [];
                }
                $indexArticle['content']      = nl2br($indexArticle['content']);
                $indexArticle['article_url']  = config('tools.article_url').$indexArticle['id'];
                unset($indexArticle['image']);
            }
        }

        $this->result['code']    = 200;
        $this->result['message'] = '获取推荐内容成功';
        $this->result['data']    =['category'=>$category,'article'=>$indexArticles];
        return $this->response->array($this->result);
    }

    /**
     * 将推荐内容加入收藏
     * @param Request $request
     * @return mixed
     */
    public function collectArticle(Request $request){
        // 自定义验证规则
        $rules = [
            'article_id' => 'required|integer|exists:articles,id',
        ];
        // 自定义提示
        $messages = [
            'article_id.required' => ['code' => 21121,  'message' => '必须传入推荐内容id', 'data' => []],
            'article_id.integer'  => ['code' => 21122,  'message' => '参数错误', 'data' => []],
            'article_id.exists'   => ['code' => 21123,  'message' => '参数错误', 'data' => []],
        ];
        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }
        $articleId = $request->get('article_id');
        $useId     = $this->user()->id;
        //封装数据,更新数据库
        try{
            if(!UserFavorite::where(['user_id'=>$useId,'article_id'=>$articleId])->first()){
                $userFavoriteClass  = new UserFavorite();
                $userFavoriteClass -> user_id    = $useId;
                $userFavoriteClass -> article_id = intval($articleId);
                $userFavoriteClass ->save();
                $this->result['code']    = 200;
                $this->result['message'] = '收藏推荐内容成功';
                $this->result['data']    =[];
                return $this->response->array($this->result);
            }else{
                $this->result['code']    = 21125;
                $this->result['message'] = '您已收藏该文章';
                return $this->response->array($this->result);
            }
        }catch (\Exception $e){
            $this->result['code']    = 21126;
            $this->result['message'] = '收藏推荐内容失败，请稍后重试';
            return $this->response->array($this->result);
        }
    }

    /**
     * 判断当前文章是否已被登陆用户加入收藏
     * @param Request $request
     * @return mixed
     */
    public function articleCollectStatus(Request $request){
        // 自定义验证规则
        $rules = [
            'article_id' => 'required|integer',
        ];
        // 自定义提示
        $messages = [
            'article_id.required' => ['code' => 21121,  'message' => '必须传入推荐内容id', 'data' => []],
            'article_id.integer'  => ['code' => 21122,  'message' => '参数错误', 'data' => []],
        ];
        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }
        $articleId = $request->get('article_id');
        $useId     = $this->user()->id;
        $sqlFindCollect =UserFavorite::where(['user_id'=>$useId,'article_id'=>$articleId])->first();
        return $sqlFindCollect ?
            $this->response->array(['code'=>200,'message'=>'ok', 'data'=>['is_collect'=>true]]):
            $this->response->array(['code'=>200,'message'=>'ok','data'=>['is_collect'=>false]]);
    }

    /**
     * 取消当前用户已收藏文章
     * @param Request $request
     * @return mixed
     */
    public function cancelCollectArticle(Request $request){
        // 自定义验证规则
        $rules = [
            'article_id' => 'required|integer',
        ];
        // 自定义提示
        $messages = [
            'article_id.required' => ['code' => 21121,  'message' => '必须传入推荐内容id', 'data' => []],
            'article_id.integer'  => ['code' => 21122,  'message' => '参数错误', 'data' => []],
        ];
        $validator = \Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $messages = $validator->errors()->toArray();
            foreach ($messages as $value) {
                $this->result['code'] = (int)$value[0]['code'];
                $this->result['message'] = $value[0]['message'];
                break;
            }
            return $this->response->array($this->result);
        }
        $articleId = $request->get('article_id');
        $useId     = $this->user()->id;
        UserFavorite::where(['user_id'=>$useId,'article_id'=>$articleId])->delete();
        $this->result['code']    = 200;
        $this->result['message'] = '取消收藏成功';
        $this->result['data']    =[];
        return $this->response->array($this->result);
    }

    /**
     * 获取用户已收藏列表
     * @return mixed
     */
    public function getUserFavorite(){
        //获取用户id
        $userId       = $this->user()->id;
        //查询用户收藏文章
        $articles = Article::join('user_favorites','article_id','=','articles.id')
                    ->where('user_favorites.user_id',$userId)
                    ->select('articles.*','user_favorites.created_at as favorite_time')
                    ->paginate(self::PAGE_SIZE);
        //查询收藏文章对应的缩略图
        if(!empty($articles)){
            foreach ($articles as $key=>$article){
                if(!$article->image->isEmpty()){
                    $articles[$key]['thumb']  = array_column($article->image->toArray(),'url');
                }else{
                    $articles[$key]['thumb']  = [];
                }
                $article['article_url']  = config('tools.article_url').$article['id'];
                unset($article['image']);
            }
        }
        $this->result['code']    = 200;
        $this->result['message'] = '获取收藏列表成功';
        $this->result['data']    =$articles;
        return $this->response->array($this->result);
    }

}